package cn.iocoder.yudao.module.system.framework.sms.core.client.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.system.framework.sms.core.chuanglan.SmsTemplates;
import cn.iocoder.yudao.module.system.framework.sms.core.chuanglan.model.request.SmsSendRequest;
import cn.iocoder.yudao.module.system.framework.sms.core.chuanglan.model.response.SmsSendResponse;
import cn.iocoder.yudao.module.system.framework.sms.core.chuanglan.util.ChuangLanSmsUtil;
import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsReceiveRespDTO;
import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsSendRespDTO;
import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsTemplateRespDTO;
import cn.iocoder.yudao.module.system.framework.sms.core.enums.SmsTemplateAuditStatusEnum;
import cn.iocoder.yudao.module.system.framework.sms.core.property.SmsChannelProperties;
import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

public class ChuanglanSmsClient extends AbstractSmsClient {

    public ChuanglanSmsClient(SmsChannelProperties properties) {
        super(properties);
        Assert.notEmpty(properties.getApiKey(), "apiKey 不能为空");
        Assert.notEmpty(properties.getApiSecret(), "apiSecret 不能为空");
    }

    @Override
    public SmsSendRespDTO sendSms(Long logId, String mobile, String apiTemplateId, List<KeyValue<String, Object>> templateParams) throws Throwable {
        //请求地址请登录253云通讯自助通平台查看或者询问您的商务负责人获取
        String smsSingleRequestServerUrl = "https://smssh1.253.com/msg/v1/send/json";
        //状态报告
        String report = "true";

        String signed = "";

        String templateString = SmsTemplates.valueOf(apiTemplateId).getValue();

        // 创建数据模型
        Map<String, Object> dataModel = new HashMap<>();
        for (KeyValue<String, Object> param : templateParams){
            dataModel.put(param.getKey(), param.getValue());
            if (param.getKey().equals("signed")){
                signed = (String) param.getValue();
            }
        }

        String msg = StrUtil.format(templateString, dataModel);

        if (!signed.isEmpty()){
            msg = msg + "【" + signed + "】";
        }

        SmsSendRequest smsSingleRequest = new SmsSendRequest(properties.getApiKey(), properties.getApiSecret(), msg, mobile, report);

        String requestJson = JSON.toJSONString(smsSingleRequest);

        System.out.println("before request string is: " + requestJson);

        String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);

        System.out.println("response after request result is :" + response);

        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

        System.out.println("response  toString is :" + smsSingleResponse);

        assert smsSingleResponse != null;
        return new SmsSendRespDTO().setSuccess(Objects.equals(smsSingleResponse.getCode(), "0")).setSerialNo(StrUtil.uuid())
                .setApiRequestId(smsSingleResponse.getCode()).setApiCode(smsSingleResponse.getErrorMsg());
    }

    @Override
    public List<SmsReceiveRespDTO> parseSmsReceiveStatus(String text) {
        JSONArray statuses = JSONUtil.parseArray(text);
        // 字段参考
        return convertList(statuses, status -> {
            JSONObject statusObj = (JSONObject) status;
            return new SmsReceiveRespDTO()
                    .setSuccess("SUCCESS".equals(statusObj.getStr("report_status"))) // 是否接收成功
                    .setErrorCode(statusObj.getStr("errmsg")) // 状态报告编码
                    .setMobile(statusObj.getStr("mobile")) // 手机号
                    .setReceiveTime(statusObj.getLocalDateTime("user_receive_time", null)) // 状态报告时间
                    .setSerialNo(statusObj.getStr("sid")); // 发送序列号
        });
    }

    @Override
    public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable {
        SmsTemplates selected = SmsTemplates.valueOf(apiTemplateId);
        return new SmsTemplateRespDTO().setId(selected.getKey()).setContent(selected.getValue())
                .setAuditStatus(SmsTemplateAuditStatusEnum.SUCCESS.getStatus()).setAuditReason("");
    }
}
